package com.kexio.user.controller;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.OperatingSystemMXBean;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.kexio.auth.annotation.RequiresPermission;
import com.kexio.common.dto.Result;
import com.kexio.user.service.SystemMonitorService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * 系统监控控制器
 *
 * 📊 提供系统监控相关的API接口：
 * - 租户隔离监控
 * - 缓存键格式验证
 * - 系统健康检查
 * - 监控仪表板数据
 *
 * @author Kexio Team
 * @since 2.2.0
 */
@RestController
@RequestMapping("/monitor")
@Tag(name = "系统监控", description = "系统运行状态监控接口")
public class SystemMonitorController {

    private static final Logger logger = LoggerFactory.getLogger(SystemMonitorController.class);

    @Autowired
    private SystemMonitorService systemMonitorService;

    /**
     * 获取系统资源信息（为前端监控页面提供）
     */
    @GetMapping("/system-resources")
    @RequiresPermission("monitor:system:query")
    @Operation(summary = "获取系统资源信息", description = "获取CPU、内存、磁盘等系统资源使用情况")
    public Result<Map<String, Object>> getSystemResources() {
        logger.debug("💻 获取系统资源信息");
        
        Map<String, Object> resources = new HashMap<>();
        
        // CPU 信息
        OperatingSystemMXBean osBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        double systemLoadAverage = osBean.getSystemLoadAverage();
        int availableProcessors = osBean.getAvailableProcessors();
        double cpuUsage = systemLoadAverage > 0 ? (systemLoadAverage / availableProcessors) * 100 : 0;
        
        resources.put("cpuUsage", Math.min(100, cpuUsage));
        resources.put("cpuCores", availableProcessors);
        resources.put("loadAverage", systemLoadAverage);
        
        // 内存信息
        MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
        long heapUsed = memoryBean.getHeapMemoryUsage().getUsed();
        long heapMax = memoryBean.getHeapMemoryUsage().getMax();
        double memoryUsage = (double) heapUsed / heapMax * 100;
        
        resources.put("memoryUsage", memoryUsage);
        resources.put("totalMemory", heapMax / (1024 * 1024)); // MB
        resources.put("usedMemory", heapUsed / (1024 * 1024)); // MB
        resources.put("freeMemory", (heapMax - heapUsed) / (1024 * 1024)); // MB
        
        // JVM 信息
        long uptimeMillis = ManagementFactory.getRuntimeMXBean().getUptime();
        resources.put("jvmUptime", uptimeMillis);
        resources.put("uptime", uptimeMillis / 1000); // 秒
        
        // 磁盘信息（简化版）
        java.io.File root = new java.io.File("/");
        long totalSpace = root.getTotalSpace();
        long freeSpace = root.getFreeSpace();
        long usedSpace = totalSpace - freeSpace;
        
        Map<String, Object> diskInfo = new HashMap<>();
        diskInfo.put("path", "/");
        diskInfo.put("total", totalSpace / (1024 * 1024 * 1024)); // GB
        diskInfo.put("used", usedSpace / (1024 * 1024 * 1024)); // GB
        diskInfo.put("free", freeSpace / (1024 * 1024 * 1024)); // GB
        diskInfo.put("usage", totalSpace > 0 ? (double) usedSpace / totalSpace * 100 : 0);
        
        java.util.List<Map<String, Object>> diskInfos = new ArrayList<>();
        diskInfos.add(diskInfo);
        resources.put("diskInfos", diskInfos);
        
        // 缓存统计（如果有Redis）
        Map<String, Object> cacheStats = new HashMap<>();
        if (systemMonitorService != null) {
            // ✓ 保留此catch：获取缓存统计失败时设置默认值
            try {
                Map<String, Object> tenantMetrics = systemMonitorService.getTenantIsolationMetrics();
                cacheStats.put("totalKeys", tenantMetrics.get("globalCacheKeyCount"));
            } catch (Exception e) {
                cacheStats.put("totalKeys", 0);
            }
        }
        resources.put("cacheStats", cacheStats);
        
        resources.put("timestamp", System.currentTimeMillis());
        
        return Result.success("获取成功", resources);
    }

    /**
     * 获取租户隔离监控指标
     */
    @GetMapping("/tenant-isolation")
    @RequiresPermission("monitor:tenant:query")
    @Operation(summary = "获取租户隔离监控", description = "获取租户缓存隔离、命中率等监控指标")
    public Result<Map<String, Object>> getTenantIsolationMetrics() {
        logger.debug("📊 获取租户隔离监控指标");
        Map<String, Object> metrics = systemMonitorService.getTenantIsolationMetrics();
        return Result.success("获取成功", metrics);
    }

    /**
     * 获取缓存键格式验证报告
     */
    @GetMapping("/cache-key-validation")
    @RequiresPermission("monitor:cache:query")
    @Operation(summary = "获取缓存键验证报告", description = "验证缓存键命名规范和格式合规性")
    public Result<Map<String, Object>> getCacheKeyValidationReport() {
        logger.debug("🔍 获取缓存键格式验证报告");
        Map<String, Object> report = systemMonitorService.getCacheKeyValidationReport();
        return Result.success("获取成功", report);
    }

    /**
     * 获取系统健康检查
     */
    @GetMapping("/health")
    @RequiresPermission("monitor:health:query")
    @Operation(summary = "获取系统健康状态", description = "检查系统各组件运行状态")
    public Result<Map<String, Object>> getSystemHealth() {
        logger.debug("🏥 获取系统健康状态");
        Map<String, Object> health = systemMonitorService.getSystemHealth();
        return Result.success("获取成功", health);
    }

    /**
     * 获取监控仪表板数据
     */
    @GetMapping("/dashboard")
    @RequiresPermission("monitor:dashboard:query")
    @Operation(summary = "获取监控仪表板", description = "获取系统监控的综合数据")
    public Result<Map<String, Object>> getMonitorDashboard() {
        logger.debug("📈 获取监控仪表板数据");
        Map<String, Object> dashboard = systemMonitorService.getMonitorDashboard();
        return Result.success("获取成功", dashboard);
    }
}

